package com.cpit.platform.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cpit.platform.common.constant.SystemConstant;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.common.utils.BeanUtil;
import com.cpit.platform.dao.AuthorityRepository;
import com.cpit.platform.dao.RoleRepository;
import com.cpit.platform.dao.RoleToAuthorityRepository;
import com.cpit.platform.dto.Authority;
import com.cpit.platform.dto.Role;
import com.cpit.platform.log.LogOperator;
import com.cpit.platform.service.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	
	private final String loggerName = this.getClass().getName();
	
	@Autowired
	private RoleRepository rep = null;
	
	@Autowired
	private AuthorityRepository authRep = null;
	
	@Autowired
	private RoleToAuthorityRepository rtoARep = null;
	
	public List<Role> findAll() {
		return rep.findAll();
	}
	
	public void create(Role data) throws Exception {
		if(data.getId() != null && data.getId() > 0) {
			LogOperator.info(loggerName, "create role, need delete role anth mappiong " + data.getId());
			//rtoARep.deleteByRoleId(data.getId());
		}
		Role fbN = rep.findByName(data.getName());
		if(fbN != null) {
			throw new Exception("同名角色已经存在！");
		}
		//renderAuthList(data);
		rep.save(data);
	}
	
	public void modify(Role data) throws Exception {
		if(data.getId() != null && data.getId() > 0) {
			LogOperator.info(loggerName, "create role, need delete role anth mappiong " + data.getId());
			//rtoARep.deleteByRoleId(data.getId());
		}
		checkUniqueConstraint(data);
		rep.save(data);
	}

	private void checkUniqueConstraint(Role role) throws  Exception {
		Role rool1 = rep.findByName(role.getName());
		if(rool1 != null && !role.getId().equals(rool1.getId())) {
			LogOperator.err(loggerName,"角色名称已存在:" + role.getName());
			throw new Exception("角色名称已存在");
		}
	}

	public void delete(Role data) throws Exception {
		rep.delete(data);
	}
	
	public List<Role> findByCondition(int page, 
			int size, 
			String order, 
			String orderBy, 
			String pattern) {
		if(orderBy == null || orderBy.length() == 0) {
			orderBy = "id";
		}
		Direction der = order.equals(SystemConstant.DIRECTION_ASC) ? Direction.ASC : Direction.DESC;
		PageRequest request = new PageRequest(page - 1, size, new Sort(der, orderBy));
		Page<Role> ret = rep.findByNameContaining(pattern, request);
		return ret.getContent();
	}
	
	@SuppressWarnings("rawtypes")
	public TableJsonData findByConditionJqg(TableDataQueryCondition cond) {
		if(cond.getSidx() == null || cond.getSidx().length() == 0) {
			cond.setSidx("id");
		}
		Direction der = null;
		if(cond.getSord() == null || cond.getSord().length() == 0) {
			der = Direction.ASC;
		} else 
			der = cond.getSord().equals(SystemConstant.DIRECTION_ASC) ? Direction.ASC : Direction.DESC;
		PageRequest request = new PageRequest(cond.getPageNumber() - 1, cond.getRowsNumber(), 
				new Sort(der, cond.getSidx()));
		Page<Role> ret = rep.findByNameContaining(BeanUtil.getStringIdentifyNull(cond.getQueryCond().get("pattern")), request);
		return new TableJsonData(cond, ret.getTotalElements(), ret.getContent());
	}
	
	protected void renderAuthList(Role role) {
		List<Authority> rRs = role.getAuthorities();
		List<Authority> rs = new ArrayList<Authority>();
		if(rRs != null && rRs.size() > 0) {
			for(Authority a : rRs) {
				Authority auth = authRep.findById(a.getId());
				rs.add(auth);
			}
		}
		role.setAuthorities(rs);
	}
	
}
